package ld.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ld.mapper.DeptMapper;
import ld.mapper.EmpMapper;
import ld.pojo.Emp;
import ld.pojo.EmpExample;
import ld.vo.EmpVo;
import ld.utils.PageResult;
import ld.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Liudao
 * @Date: 2022-08-04-15:05
 * @Description:
 */
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<Emp> findAll() {
        return empMapper.selectByExample(null);
    }

    @Override
    public PageResult<Emp> findBypage(int page, int pagesize) {
        //开始分页
        PageHelper.startPage(page, pagesize);
        //得到全部
        List<Emp> emps = empMapper.selectByExample(null);
        for (Emp emp : emps) {
            emp.setDname(deptMapper.selectByPrimaryKey(emp.getDid()).getDname());
        }
        //得到pageinfo对象
        PageInfo<Emp> empPageInfo = new PageInfo<>(emps);
        return new PageResult<>(empPageInfo.getTotal(), empPageInfo.getList());
    }

    @Override
    public PageResult<Emp> search(int page, int pagesize, EmpVo vo) {
        PageHelper.startPage(page, pagesize);
        //定义条件查询实例对象
        EmpExample empExample = new EmpExample();
        //得到关联的条件对象
        EmpExample.Criteria criteria = empExample.createCriteria();
        //封装查询条件
         if (!StringUtils.isEmpty(vo.getEname())) {
            criteria.andEnameLike("%" + vo.getEname() + "%");
        }
        if (!StringUtils.isEmpty(vo.getCity())) {
            criteria.andCityLike("%" + vo.getCity() + "%");
        }
        if (vo.getDid() != 0) {
            criteria.andDidEqualTo(vo.getDid());
        }
        List<Emp> emps = empMapper.selectByExample(empExample);
        //将部门与员工结合
        for (Emp emp : emps) {
            emp.setDname(deptMapper.selectByPrimaryKey(emp.getDid()).getDname());
        }
        PageInfo<Emp> empPageInfo = new PageInfo<>(emps);
        return new PageResult<>(empPageInfo.getTotal(),empPageInfo.getList());
    }

    @Override
    public void add(Emp emp1) {
        empMapper.insert(emp1);
    }

    @Override
    public void update(Emp emp1) {
        empMapper.updateByPrimaryKey(emp1);   
    }

    @Override
    public void delete(String[] eids) {
        EmpExample empExample = new EmpExample();
        EmpExample.Criteria criteria = empExample.createCriteria();
        List<Integer> list = new ArrayList<>();
        for (String eid : eids) {
            list.add(new Integer(eid));
        }
        criteria.andEidIn(list);
        empMapper.deleteByExample(empExample);
    }
}
